from pydantic import BaseModel, Field, validator
from datetime import datetime
from typing import List, Optional, Dict, Any, ForwardRef


class PermissionBase(BaseModel):
    """权限基础模型"""
    name: str = Field(..., min_length=1, max_length=100, description="权限名称")
    code: str = Field(..., min_length=1, max_length=100, description="权限编码")
    type: str = Field(..., description="权限类型：menu(菜单), button(按钮), api(接口)")
    parent_id: int = Field(default=0, description="父级权限ID")
    path: Optional[str] = Field(None, max_length=255, description="路由路径")
    component: Optional[str] = Field(None, max_length=255, description="组件路径")
    icon: Optional[str] = Field(None, max_length=100, description="图标")
    sort_order: int = Field(default=0, description="排序")
    is_visible: bool = Field(default=True, description="是否可见")
    is_active: bool = Field(default=True, description="是否激活")
    remark: Optional[str] = Field(None, description="备注")

    @validator('type')
    def validate_type(cls, v):
        """验证权限类型"""
        if v not in ['menu', 'button', 'api']:
            raise ValueError('权限类型必须是 menu、button 或 api')
        return v

    @validator('code')
    def validate_code(cls, v):
        """验证权限编码格式"""
        if not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('权限编码只能包含字母、数字、下划线和连字符')
        return v


class PermissionCreateInput(PermissionBase):
    """权限创建输入模型"""
    pass


class PermissionUpdate(BaseModel):
    """权限更新模型"""
    name: Optional[str] = Field(None, min_length=1, max_length=100, description="权限名称")
    code: Optional[str] = Field(None, min_length=1, max_length=100, description="权限编码")
    type: Optional[str] = Field(None, description="权限类型")
    parent_id: Optional[int] = Field(None, description="父级权限ID")
    path: Optional[str] = Field(None, max_length=255, description="路由路径")
    component: Optional[str] = Field(None, max_length=255, description="组件路径")
    icon: Optional[str] = Field(None, max_length=100, description="图标")
    sort_order: Optional[int] = Field(None, description="排序")
    is_visible: Optional[bool] = Field(None, description="是否可见")
    is_active: Optional[bool] = Field(None, description="是否激活")
    remark: Optional[str] = Field(None, description="备注")

    @validator('type')
    def validate_type(cls, v):
        """验证权限类型"""
        if v is not None and v not in ['menu', 'button', 'api']:
            raise ValueError('权限类型必须是 menu、button 或 api')
        return v

    @validator('code')
    def validate_code(cls, v):
        """验证权限编码格式"""
        if v is not None and not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('权限编码只能包含字母、数字、下划线和连字符')
        return v


class PermissionInfo(BaseModel):
    """权限信息模型"""
    id: int = Field(description="权限ID")
    name: str = Field(description="权限名称")
    code: str = Field(description="权限编码")
    type: str = Field(description="权限类型")
    parent_id: int = Field(description="父级权限ID")
    path: Optional[str] = Field(None, description="路由路径")
    component: Optional[str] = Field(None, description="组件路径")
    icon: Optional[str] = Field(None, description="图标")
    sort_order: int = Field(description="排序")
    is_visible: bool = Field(description="是否可见")
    is_active: bool = Field(description="是否激活")
    is_system: bool = Field(description="是否系统权限")
    remark: Optional[str] = Field(None, description="备注")
    created_at: datetime = Field(description="创建时间")
    updated_at: datetime = Field(description="更新时间")

    class Config:
        from_attributes = True


class PermissionTreeItem(BaseModel):
    """权限树节点模型"""
    id: int = Field(description="权限ID")
    name: str = Field(description="权限名称")
    code: str = Field(description="权限编码")
    type: str = Field(description="权限类型")
    parent_id: int = Field(description="父级权限ID")
    path: Optional[str] = Field(None, description="路由路径")
    component: Optional[str] = Field(None, description="组件路径")
    icon: Optional[str] = Field(None, description="图标")
    sort_order: int = Field(description="排序")
    is_visible: bool = Field(description="是否可见")
    children: List['PermissionTreeItem'] = Field(default=[], description="子权限")

    class Config:
        from_attributes = True


# 解决循环引用
PermissionTreeItem.model_rebuild()


class PermissionListResponse(BaseModel):
    """权限列表响应模型"""
    total: int = Field(description="总数")
    items: List[PermissionInfo] = Field(description="权限列表")


class PermissionTreeResponse(BaseModel):
    """权限树响应模型"""
    items: List[PermissionTreeItem] = Field(description="权限树")


class PermissionCreatedResponse(BaseModel):
    """权限创建成功响应模型"""
    id: int = Field(description="权限ID")
    name: str = Field(description="权限名称")
    code: str = Field(description="权限编码")


class PermissionBatchUpdate(BaseModel):
    """权限批量更新模型"""
    ids: List[int] = Field(..., description="权限ID列表")
    is_active: Optional[bool] = Field(None, description="是否激活")
    is_visible: Optional[bool] = Field(None, description="是否可见")


class PermissionQueryParams(BaseModel):
    """权限查询参数模型"""
    name: Optional[str] = Field(None, description="权限名称")
    code: Optional[str] = Field(None, description="权限编码")
    type: Optional[str] = Field(None, description="权限类型")
    parent_id: Optional[int] = Field(None, description="父级权限ID")
    is_active: Optional[bool] = Field(None, description="是否激活")
    is_visible: Optional[bool] = Field(None, description="是否可见")
    is_system: Optional[bool] = Field(None, description="是否系统权限")
